package basic.serializeDemo;

import java.io.*;

/**
 * @Description: TODO 使用Serializable 序列化和反序列化
 * @Author: wzj
 * @Date: 2020/11/26 18:48
 */
public class SerializeDemo {
    public static void main(String[] args) {
        try {
            serialize();
//            deserialize();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void serialize() throws IOException {
        //序列化
        SerializeObj serializeObj=new SerializeObj("测试",20,1);
        ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream("C:\\Users\\007\\Desktop\\testObj.txt"));
        objectOutputStream.writeObject(serializeObj);
        objectOutputStream.close();
        System.out.println("序列化："+serializeObj.toString());
    }
    public static void deserialize() throws IOException, ClassNotFoundException {
        //反序列化
        ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream("C:\\Users\\007\\Desktop\\testObj.txt"));
        SerializeObj serializeObj1=(SerializeObj) objectInputStream.readObject();
        objectInputStream.close();
        System.out.println("反序列化："+serializeObj1.toString());
    }
}

class SerializeObj implements Serializable{
    private String name;
    private int age;
    private transient int id;//transient序列化的时候不保存值

    public SerializeObj() {
    }

    public SerializeObj(String name, int age, int id) {
        this.name = name;
        this.age = age;
        this.id = id;
    }

    @Override
    public String toString() {
        return "SerializeObj{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", id=" + id +
                '}';
    }
}